﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using TfsGiggle.Core;

namespace TfsGiggle.Search
{
    /// <summary>
    /// Interaction logic for TfsGiggleSearchControl.xaml
    /// </summary>
    public partial class TfsGiggleSearchControl : UserControl
    {
        private ObservableCollection<TfsGiggleFile> _tfsGiggleFiles = new ObservableCollection<TfsGiggleFile>();

        /// <summary>
        /// Control
        /// </summary>
        public TfsGiggleSearchControl()
        {
            InitializeComponent();
        }

        /// <summary>
        /// The search results
        /// </summary>
        public ObservableCollection<TfsGiggleFile> TfsGiggleFiles
        {
            get
            {
                return _tfsGiggleFiles;
            }
        }

        /// <summary>
        /// Open the document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ListViewHandleDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var file = (TfsGiggleFile)((ListViewItem)sender).Content;
                var filePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(file.Name));
                var contents = TfsGiggleSearchPackage.Instance.GetFile(file.TeamProjectCollectionId, file.Name);
                if (!string.IsNullOrWhiteSpace(contents))
                {
                    File.WriteAllText(filePath, contents);
                    OpenFile(filePath);
                }
            }
            catch (Exception ex)
            {
                ActivityLog.LogError("Exception caught in TfsGiggle", ex.ToString());
                throw;
            }
        }

        internal static void OpenFile(string path)
        {
            IVsUIShellOpenDocument service = Package.GetGlobalService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
            Guid empty = Guid.Empty;
            Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider;
            uint num;
            IVsWindowFrame frame;
            IVsUIHierarchy hierarchy;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(service.OpenDocumentViaProject(path, ref empty, out provider, out hierarchy, out num, out frame));
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hierarchy.SetProperty(num, -2003, path));
            if (frame != null)
            {
                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.Show());
            }
        }
    }
}
